<template>
  <div class="vue-bank">
       <label>
            <span>{{title}}</span>
            <input type="tel"
            v-model.trim="cardNumber"
            @blur="blurs"
            :placeholder="placeholder"
            autocomplete="off"
            />
        </label>
        <label v-if="show">
            <span>所属银行</span>
            <input type="text"
            v-model.trim="bankName"
            readonly  
            unselectable="on"
            autocomplete="off"
            />
        </label>
  </div>
</template>
<script>
import axios from 'axios';
import getBank from './bank';
export default {
  name: "bank",
  props: {
    // lable文字
    title: {
      type: String,
      default: ""
    },
    // 提示文字
    placeholder: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
        list:[],
        show:false,
        cardNumber:"",
        bankName:""
    };
  },
  methods: {
      //失去焦点请求
      blurs(){
          const vm = this;
          //检测 银行卡号是否存在
          const http = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardBinCheck=true";
          axios.get(http, {
            params: {
              cardNo: vm.cardNumber
            }
          })
          .then(function (response) {
            if(response.status == 200){
                if(response.data.validated) {
                  vm.show = true;
                  vm.bankName = vm.getBank(response.data.bank);
                  vm.$emit("callback", {
                    cardNumber:vm.cardNumber,
                    bankName:vm.bankName
                  });
                }else {
                  vm.show = false;
                  vm.$notify({ type: 'danger', message: '银行卡号输入不合法' });
                  vm.cardNumber="";
                }
            }else {
              vm.$notify({ type: 'danger', message: '啊偶！断网了...' });
            }
          })
          .catch(function (error) {
            console.log(error);
          })
          .then(function () {
            // always executed
          });
      },
      //计算 最终搜索的银行名字
      getBank(str){
        const vm = this;
        let name = "";
        vm.list.map(function(currentValue,index,arr){
          if(currentValue.value == str){
            name = currentValue.text;
          }
        })
        return name
      }
  },
  mounted() {
    const vm = this;
    vm.list = getBank.getBank();
  },
  computed:{
    
  }
};
</script>
<style lang="scss" scoped>
    .vue-bank {
        label {
            height: 90px;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #eee;
            span {
                font-size: 30px;
                color: #333;
                width: 150px;
            }
            input {
                height: 100%;
                width: calc(100% - 150px);
                border:0;
                background-color: transparent;
            }
        }
    }
</style>